package leetcode;

import util.Tree;
import util.TreeNode;

/**
 * @Project : AlgorithmLearning
 * @Package : Leetcode
 * @File : Q0543.java
 * @Author : WangRuoyu
 * @Date 2023/11/20 22:51
 */


public class Q0543 {
    int d = 0;

    private int dfs(TreeNode root) {
        if (root == null) return 0;
        int l = dfs(root.left);
        int r = dfs(root.right);
        d = Math.max(l + r, d);
        return Math.max(l, r) + 1;
    }

    public int diameterOfBinaryTree(TreeNode root) {
        dfs(root);
        return d;
    }

    public static void main(String[] args) {
        Q0543 sl = new Q0543();
        TreeNode root = Tree.createTreeByPreorderAndInorder(new int[]{1, 2, 4, 5, 3}, new int[]{4, 2, 5, 1, 3});
        System.out.println(sl.diameterOfBinaryTree(root));
    }
}